<?php
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.delivery.cdn_delivery_explain");
class delivery extends \ns_model\delivery\cdn_delivery_explain
{
    private $series_view_type = array(1,2,3);//媒资类型  1 电视剧 2 综艺 3 动漫
    private $country = array( //地区编码
        1 => '内地',
        2 => '港台',
        3 => '韩日',
        4 => '欧美',
        5 => '东南亚',
    );

    public function explain()
    {
        $fuc_name = (string)$this->get_c2_type();
        if(empty($fuc_name))
        {
            return $this->write_log_return('C2类型参数为空', NS_CDS_FAIL);
        }
        return $this->save_exec_log($this->$fuc_name());
    }

    /**
     * 注入CDN，主媒资不注入
     * @return array
     */
    public function video()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }
    /**
     * 注入CDN，分集不注入
     * @return array
     */
    public function index()
    {
        return $this->is_ok(NS_CDS_CDN_SUCCE, '成功');
    }

    /**
     * 单剧集与多剧集，即电影与电视剧等统一按照电视剧方式进行注入CDN
     * 片源注入CDN
     * @return array
     */
    public function media()
    {
        $action = $this->get_c2_info('action');
        if ($action === NS_CDS_DELETE)
        {
            return $this->media_destroy();
        }
        else
        {
            $action = "REGIST";
        }
        //判断是否处于发布失败状态,则重新发布。不需要走注入流程
        if($this->get_c2_info('status') == NS_CDS_CDN_LINE_FAIL)
        {
            #TODO 联调预留
            $c2_publish_id = $this->get_guid();
            $params = array(
                'nns_task_type' => "Movie",//媒资类型
                'nns_action' => 'ONLINE', //发布
                'nns_content' => '',
                'nns_task_id' => $this->get_c2_info('id'),
                'nns_task_name' => $this->get_c2_info('name'),
            );
            $exec_re = $this->execute($params,$c2_publish_id,'Publish');
            return $this->save_exec_log($exec_re);
        }
        $arr_video_info = $this->get_video_info();
        if (empty($arr_video_info))
        {
            return $this->write_log_return("C2任务video数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        //获取主媒资注入ID
        $cdn_video_import_id = $this->get_video_cdn_import_id(NS_CDS_VIDEO);
        if (empty($cdn_video_import_id))
        {
            return $this->write_log_return("C2任务生成主媒资CDN注入ID获取失败", NS_CDS_FAIL);
        }

        $arr_index_info = $this->get_index_info();
        if (empty($arr_index_info))
        {
            return $this->write_log_return("C2任务index数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        //获取分集注入ID
        $cdn_index_import_id = $this->get_video_cdn_import_id(NS_CDS_INDEX);
        if (empty($cdn_index_import_id))
        {
            return $this->write_log_return("C2任务生成分集CDN注入ID获取失败", NS_CDS_FAIL);
        }

        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        $cdn_import_id = $this->get_video_cdn_import_id();
        if (empty($cdn_import_id))
        {
            return $this->write_log_return("C2任务生成片源CDN注入ID获取失败", NS_CDS_FAIL);
        }

        //获取播控平台资源库栏目--用于获取栏目对于关系与资源类型
        $categorys = $this->get_category_info();
        if($categorys['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($categorys['reason'],NS_CDS_FAIL);
        }
        $category_name = '';
        foreach ($categorys['data_info'] as $category)
        {
            if ((string)$category['id'] == (string)$arr_video_info['base_info']['nns_category_id'])
            {
                $category_name = $category['name'];
                break;
            }
        }
        //片源清晰度
        $is_hd = 0;
        if(!empty($arr_media_info['base_info']['nns_mode']) && in_array(strtolower($arr_media_info['base_info']['nns_mode']),array('low','std')))
        {
            $is_hd = 1;
        }
        //文件大小
        $file_size = '1';
        if((int)$this->get_c2_info('file_size') > 0)
        {
            $file_size = $this->get_c2_info('file_size');
        }
        elseif (strlen($this->get_c2_info('file_size')) <= 0 && (int)$arr_media_info['base_info']['nns_file_size'] > 0)
        {
            $file_size = $arr_media_info['base_info']['nns_file_size'];
        }
        //片源文件地址
        $file_path = $arr_media_info['base_info']['nns_url'];
        if(!empty($this->get_c2_info('file_path')))
        {
            if(isset($this->arr_sp_config['media_ftp']) && !empty($this->arr_sp_config['media_ftp']))
            {
                $file_path = rtrim($this->arr_sp_config['media_ftp'],"/") . "/" . ltrim($this->get_c2_info('file_path'), "/");
            }
            else
            {
                $file_path = $this->get_c2_info('file_path');
            }
        }

        // C2消息ID
        $Sequence = $this->get_guid();
        //地区编码
        foreach ($this->country as $key=>$val)
        {
            if($val === $arr_video_info['base_info']['nns_area'])
            {
                $country = $key;
            }
            else
            {
                $country = 99;
            }
        }
        $now = time();
        $data = array(
            //主媒资GroupAsset
            'adi:OpenGroupAsset' => array(
                array(
                    'type' => 'VODRelease',
                    'product' => 'VOD',
                    'vod:VODRelease' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'providerType' => 2,//CP类型: 1 －个人用户   2 －CP   3 －集团   4 – 联通自有系统
                            'assetID' => $cdn_video_import_id,//注入ID
                            'updateNum' => '',
                            'groupAsset' => 'Y',
                            'serialNo' => $Sequence, //C2消息ID
                            'adi:AssetLifetime' => array(  //版权时间
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                        ),
                    ),
                ),
                //分集GroupAsset
                array(
                    'type' => 'VODRelease',
                    'product' => 'VOD',
                    'vod:VODRelease' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'providerType' => 2,//CP类型: 1 －个人用户   2 －CP   3 －集团   4 – 联通自有系统
                            'assetID' => $cdn_index_import_id,//分集注入ID
                            'updateNum' => '',
                            'groupAsset' => 'Y',
                            'serialNo' => $Sequence, //C2消息ID
                            'adi:AssetLifetime' => array(
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
            //主媒资meta元数据信息
            'adi:AddMetadataAsset' => array(
                array(
                    'groupProviderID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'groupAssetID' => $cdn_video_import_id,//注入ID
                    'type' => 'Title',
                    'product' => 'VOD',
                    'vod:Title' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'assetID' => $cdn_video_import_id,//注入ID
                            'updateNum' => '',
                            'adi:AssetLifetime' => array(
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                            'vod:StarLevel' => 0,
                            'vod:Keyword' => $arr_video_info['base_info']['nns_keyword'],//关键字
                            'vod:IsAdvertise' => 0,//广告内容标识  0 非广告  1 广告内容
                            'vod:Year' => $arr_video_info['ex_info']['year'],//发行年份
                            'vod:releaseTime' => $arr_video_info['base_info']['nns_show_time'],//上映日期
                            'vod:Actor' => array(
                                array(
                                    'type' => 'Actor',
                                    'vod:LastNameFirst' => $arr_video_info['base_info']['nns_actor'],//演员
                                ),
                            ),
                            'vod:RunTime' => $arr_video_info['base_info']['nns_view_len'],//时长
                            'vod:SearchName' => $arr_video_info['base_info']['nns_pinyin'],//拼音首字母
                            'vod:EnglishName' => $arr_video_info['base_info']['nns_eng_name'],
                            'vod:Director' => array(
                                array(
                                    'vod:LastNameFirst' => $arr_video_info['base_info']['nns_director'],//导演
                                ),
                            ),
                            'vod:CountryOfOrigin' => $country,//内地=1,港台=2,韩日=3,欧美=4, 东南亚=5，其他=99
                            'vod:Items' => $arr_video_info['base_info']['nns_all_index'],//总集数
                            'vod:TitleFull' => $arr_video_info['base_info']['nns_name'],//名称
                            'vod:IsCompleted' => 0,
                            'vod:ShowType' => 'Series',
                            'vod:Priority' => 9,//内容优先级
                            'vod:Status' => 1,
                            'vod:Rating' => 0,
                            'vod:SummaryMedium' => $arr_video_info['base_info']['nns_summary'],//描述
                            'vod:Language' => $arr_video_info['base_info']['nns_language'],//语言
                        ),
                    ),
                ),
                //媒资分类信息
                array(
                    'groupProviderID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'groupAssetID' => $cdn_video_import_id,//注入ID
                    'type' => 'CategoryPath',
                    'product' => 'VOD',
                    'vod:CategoryPath' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'assetID' => $cdn_video_import_id,//注入ID
                            'updateNum' => '1',
                            'adi:AssetLifetime' => array(
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                            'vod:Category' => str_replace(array("/","|"),",",$arr_video_info['base_info']['nns_kind']),//二级分类
                            'vod:Classification' => $category_name,//一级分类
                        ),
                    ),
                ),
                //分集meta元数据信息
                array(
                    'groupProviderID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'groupAssetID' => $cdn_index_import_id,//注入ID
                    'type' => 'Title',
                    'product' => 'VOD',
                    'vod:Title' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'assetID' => $cdn_index_import_id,//注入ID
                            'updateNum' => '1',
                            'adi:AssetLifetime' => array(
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                            'vod:Status' => 1,
                            'vod:TitleFull' => !empty($arr_index_info['base_info']['nns_name']) ? $arr_index_info['base_info']['nns_name'] : $arr_video_info['base_info']['nns_name'],
                            'vod:RunTime' => $arr_index_info['base_info']['nns_time_len'],//时长
                            'vod:SummaryMedium' => $arr_index_info['base_info']['nns_summary'],//描述
                            'vod:IsAdvertise' => 0,
                            'vod:ShowType' => 'Series',
                            'vod:EpisodeID' => $arr_index_info['base_info']['nns_index'] + 1,//分集数
                        ),
                    ),
                ),
            ),
            //分集片源信息
            'adi:AcceptContentAsset' => array(
                array(
                    'metadataOnly' => 'N',
                    'fileName' => !empty($arr_media_info['base_info']['nns_name']) ? $arr_media_info['base_info']['nns_name'] : $arr_video_info['base_info']['nns_name'].'_'.($arr_index_info['base_info']['nns_index'] + 1),
                    'type' => 'Video',
                    'fileSize' => $file_size,
                    'mD5CheckSum' => '',
                    'Original_Asset_ID' => $arr_media_info['base_info']['nns_import_id'],
                    'vod:Video' => array(
                        array(
                            'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                            'assetID' => $cdn_import_id,
                            'updateNum' => '1',
                            'fileName' => !empty($arr_media_info['base_info']['nns_name']) ? $arr_media_info['base_info']['nns_name'] : $arr_video_info['base_info']['nns_name'].'_'.($arr_index_info['base_info']['nns_index'] + 1),
                            'fileSize' => $file_size,
                            'mD5CheckSum' => '',
                            'transferContentURL' => $file_path,
                            'encodingProfile' => '',
                            'encodingCode' => '',
                            'adi:AssetLifetime' => array(
                                array(
                                    'startDateTime' => date('Y-m-d'),
                                    'endDateTime' => date("Y-m-d",strtotime("+19years",$now)),
                                ),
                            ),
                            'vod:AspectRatio' => '',//宽高比例
                            'vod:HDFlag' => $is_hd,//清晰度 0 高清 1 标清
                            'vod:Brightness' => '',//亮度
                            'vod:FrameHeight' => '1080',//帧高
                            'vod:FrameWidth' => '1920',//帧宽
                            'vod:IsFinished' => 1,//是否加工完毕，如果不填写默认为成品
                            'vod:MimeType' => 1,
                            'vod:IsEdit' => 1,
                            'vod:ServiceType' => 1,//内容的应用属性
                            'vod:parentAssetID' => '',
                            'vod:NeedDRM' => 1,//是否需要DRM 1 否 0 是
                            'vod:Usage' => '1',//文件用途 正片=1,宣传片=3,片花=4,花絮=5,海报=6,主程序=8,宣传画=9,其他=7
                            'vod:VideoCodec' => '',//视频编码格式
                            'vod:Numberofframes' => '',//帧数
                            'vod:AudioCodec' => '',//音频编码格式
                            'vod:IsDRM' => 1,//是否加密文件，如果不写默认 1 非加密 0 加密
                            'vod:Duration' => $arr_media_info['base_info']['nns_file_time_len'],
                            'vod:FileType' => 1,//文件类型 1：视频,2：音频,3：图片, 程序=4,BREW=5,应用=6, 文本=7
                            'vod:Contrast' => '',//对比度
                            'vod:Bitrate' => $arr_media_info['base_info']['nns_kbps'],
                            'vod:FrameRate' => '25',//帧率
                        ),
                    ),
                ),
            ),
            'adi:AssociateContent' => array(
                array(
                    'type' => 'Video',
                    'effectiveDate' => '',
                    'groupProviderID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'groupAssetID' => $cdn_index_import_id,
                    'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'assetID' => $cdn_import_id,
                ),
            ),
            'adi:AssociateGroup' => array(
                array(
                    'effectiveDate' => '',
                    'groupProviderID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'providerID' => $arr_video_info['base_info']['nns_producer'],//原始CPID
                    'assetID' => $cdn_index_import_id,
                    'sourceGroupAssetID' => $cdn_index_import_id,
                    'targetGroupAssetID' => $cdn_video_import_id,
                ),
            ),
        );

        $xml = $this->_make_array_xml($data);

        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => $action, //行为动作
            'nns_content' => $xml,//注入XML内容
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        return $this->execute($params,$Sequence,'IngestAsset');
    }

    /**
     * 片源删除，删除CDN为同步返回删除状态
     */
    public function media_destroy()
    {
        $arr_media_info = $this->get_media_info();
        if (empty($arr_media_info))
        {
            return $this->write_log_return("C2任务media数据错误，执行注入CDN失败", NS_CDS_FAIL);
        }
        //删除之前先取消发布
        $c2_unpublish_id = $this->get_guid();
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => 'OFFLINE', //取消发布
            'nns_content' => '',
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        $exec_re = $this->execute($params,$c2_unpublish_id,'Unpublish');
        if($exec_re['ret'] != NS_CDS_SUCCE)
        {
            return $this->save_exec_log($exec_re);
        }

        //取消发布后删除
        $c2_DeleteAsset_id = $this->get_guid();
        $params = array(
            'nns_task_type' => "Movie",//媒资类型
            'nns_action' => 'DELETE', //行为动作
            'nns_content' => '',
            'nns_task_id' => $this->get_c2_info('id'),
            'nns_task_name' => $this->get_c2_info('name'),
        );
        $exec_re = $this->execute($params,$c2_DeleteAsset_id,'DeleteAsset');
        return $this->save_exec_log($exec_re);
    }
    /**
     * CDN注入统一发送器入口
     * 按项目进行自定义发送处理
     * @param $params array(
     *       'nns_task_type' =>类型,
     *       'nns_action' => 行为动作，
     *       'nns_content' => 注入XML内容
     * );
     * @param $c2_id GUID 工单ID
     * @return array('ret','reason');
     */
    public function execute($params,$c2_id,$action)
    {
        //生成CDN工单唯一ID
        $params['nns_id'] = $c2_id;
        include_once NPDIR . "np_http_curl.class.php";

//        try
//        {
            global $g_bk_web_url;
            $project = evn::get('project');
            $notify_url = trim(trim($g_bk_web_url, '/'), '\\') . "/v2/ns_api/" . $project ."/delivery/" . $this->str_sp_id . "/notify.php";
            $wsdl_addr = $this->get_project_config('ipanel_wsdl_addr');
            //wsdl走POST方式进行注入
//            $soap_client = new SOAPClient($wsdl_addr, array('trace'=>true,'cache_wsdl' =>WSDL_CACHE_NONE));

            switch ($action)
            {
                case 'IngestAsset'://注入
                    //初始化CDN注入状态
                    $cdn_code = NS_CDS_CDN_LOADING;
                    //上传工单至FTP服务器,上传至服务器根目录下
                    $task = $this->save_execute_import_content_v2($params['nns_content'], $this->arr_sp_config['xml_ftp'], true);
                    if($task['ret'] != NS_CDS_SUCCE)
                    {
                        $this->write_log_return($task['reason'], NS_CDS_FAIL);
                        return $task;
                    }
                    $local_url = $task['data_info']['base_dir'];
                    $url_arr = explode("/",$local_url);
                    //获取文件名称
                    $file_name = end($url_arr);
                    //SOAP注入参数
                    $xml_post_string  = '<?xml version="1.0" encoding="utf-8"?>';
                    $xml_post_string .= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ing="http://IngestAssetService.homed.ipanel.cn">';
                    $xml_post_string .=      '<soapenv:Header/>';
                    $xml_post_string .=      '<soapenv:Body>';
                    $xml_post_string .=          '<ing:IngestAsset>';
                    $xml_post_string .=              '<LSPID>'.$this->get_project_config('LSPID').'</LSPID>';
                    $xml_post_string .=              '<AMSID>'.$this->get_project_config('AMSID').'</AMSID>';
                    $xml_post_string .=              '<Sequence>'.$c2_id.'</Sequence>';
                    $xml_post_string .=              '<FtpPath>'.$this->arr_sp_config['xml_ftp'].'</FtpPath>';
                    $xml_post_string .=              '<AdiFileName>'.$file_name.'</AdiFileName>';
                    $xml_post_string .=              '<NotifyUrl>'.$notify_url.'</NotifyUrl>';
                    $xml_post_string .=          '</ing:IngestAsset>';
                    $xml_post_string .=      '</soapenv:Body>';
                    $xml_post_string .= '</soapenv:Envelope>';

                    $this->write_log_return("CDN调用：" . $wsdl_addr . "，IngestAsset参数：" . $xml_post_string);

//                    $client_re = $soap_client->__doRequest($xml_post_string,$wsdl_addr,'IngestAsset',1,0);

                    $curl = new np_http_curl_class();
                    $client_re = $curl->post($wsdl_addr,$xml_post_string);
                    $this->write_log_return("IngestAsset-CDN同步返回：".var_export($client_re,true));
                    $client_re = $this->parse_notify_xml($client_re);
                    $this->write_log_return("IngestAsset-CDN反馈XML解析结果：".var_export($client_re,true));
                    if(is_array($client_re) && !empty($client_re))
                    {
                        $client_code = $client_re['ResultCode'];
                    }
                    else
                    {
                        $client_code = NS_CDS_FAIL;
                    }

                    if($client_code == NS_CDS_SUCCE)
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $reason = "发送成功";
                    }
                    else
                    {
                        $import_code = NS_CDS_CDN_FAIL;
                        $cdn_code = NS_CDS_CDN_FAIL;
                        $ipanel_code = array(
                            '1' => 'prc命令调用参数出错,PPC本身参数不和规范',
                            '2' => 'adi文件加载失败',
                            '3' => 'adi文件解析失败',
                        );
                        $reason = isset($ipanel_code[$client_code]) ? $client_code.$ipanel_code[$client_code] : $client_re['ResultMsg'];
                    }
                    $this->write_log_return($reason, $cdn_code);
                    break;
                case 'Publish'://发布
                    $cdn_code = NS_CDS_CDN_LINE_LOADING;
                    $local_url = '';
                    $arr_video_info = $this->get_video_info();

                    $xml_post_string  = '<?xml version="1.0" encoding="utf-8"?>';
                    $xml_post_string .= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ing="http://IngestAssetService.homed.ipanel.cn">';
                    $xml_post_string .=      '<soapenv:Header/>';
                    $xml_post_string .=      '<soapenv:Body>';
                    $xml_post_string .=          '<ing:Publish>';
                    $xml_post_string .=              '<LSPID>'.$this->get_project_config('LSPID').'</LSPID>';
                    $xml_post_string .=              '<AMSID>'.$this->get_project_config('AMSID').'</AMSID>';
                    $xml_post_string .=              '<Sequence>'.$c2_id.'</Sequence>';
                    $xml_post_string .=              '<AssetId>'.$this->get_video_cdn_import_id().'</AssetId>';
                    $xml_post_string .=              '<ProviderID>'.$arr_video_info['base_info']['nns_producer'].'</ProviderID>';
                    $xml_post_string .=              '<PPVId></PPVId>';
                    $xml_post_string .=              '<ColumnId>'.$this->get_project_config('ColumnId').'</ColumnId>';
                    $xml_post_string .=          '</ing:Publish>';
                    $xml_post_string .=      '</soapenv:Body>';
                    $xml_post_string .= '</soapenv:Envelope>';

                    $this->write_log_return("CDN调用：" . $wsdl_addr . "，Publish参数：" . $xml_post_string);

//                    $client_re = $soap_client->__doRequest($xml_post_string,$wsdl_addr,'Publish',1,0);
                    $curl = new np_http_curl_class();
                    $client_re = $curl->post($wsdl_addr,$xml_post_string);
                    $this->write_log_return("Publish-CDN同步返回：".var_export($client_re,true));
                    $client_re = $this->parse_notify_xml($client_re);
                    $this->write_log_return("Publish-CDN反馈XML解析结果：".var_export($client_re,true));
                    if(is_array($client_re) && !empty($client_re))
                    {
                        $client_code = $client_re['ResultCode'];
                    }
                    else
                    {
                        $client_code = NS_CDS_FAIL;
                    }

                    if($client_code == NS_CDS_SUCCE)
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $reason = "发送成功";
                        $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
                    }
                    else
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $cdn_code = NS_CDS_CDN_LINE_FAIL;
                        $ipanel_code = array(
                            '1' => 'prc命令调用参数出错,PPC本身参数不和规范',
                            '6' => '资产（id）不存在',
                            '7' => '套餐包（id）不存在',
                            '8' => '服务内部错误，各个进程间协作问题',
                        );
                        $reason = isset($ipanel_code[$client_code]) ? $client_code.$ipanel_code[$client_code] : $client_re['ResultMsg'];
                    }
                    $this->write_log_return($reason, $cdn_code);
                    break;
                case 'Unpublish'://取消发布
                    $cdn_code = NS_CDS_CDN_NOTIFY_SUCCE;//初始化成功
                    $local_url = '';
                    $arr_video_info = $this->get_video_info();

                    $xml_post_string  = '<?xml version="1.0" encoding="utf-8"?>';
                    $xml_post_string .= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ing="http://IngestAssetService.homed.ipanel.cn">';
                    $xml_post_string .=      '<soapenv:Header/>';
                    $xml_post_string .=      '<soapenv:Body>';
                    $xml_post_string .=          '<ing:Unpublish>';
                    $xml_post_string .=              '<LSPID>'.$this->get_project_config('LSPID').'</LSPID>';
                    $xml_post_string .=              '<AMSID>'.$this->get_project_config('AMSID').'</AMSID>';
                    $xml_post_string .=              '<Sequence>'.$c2_id.'</Sequence>';
                    $xml_post_string .=              '<AssetId>'.$this->get_video_cdn_import_id().'</AssetId>';
                    $xml_post_string .=              '<ProviderID>'.$arr_video_info['base_info']['nns_producer'].'</ProviderID>';
                    $xml_post_string .=          '</ing:Unpublish>';
                    $xml_post_string .=      '</soapenv:Body>';
                    $xml_post_string .= '</soapenv:Envelope>';

                    $this->write_log_return("CDN调用：" . $wsdl_addr . "，Unpublish参数：" . $xml_post_string);

//                    $client_re = $soap_client->__doRequest($xml_post_string,$wsdl_addr,'Unpublish',1,0);
                    $curl = new np_http_curl_class();
                    $client_re = $curl->post($wsdl_addr,$xml_post_string);
                    $this->write_log_return("Unpublish-CDN同步返回：".var_export($client_re,true));
                    $client_re = $this->parse_notify_xml($client_re);
                    $this->write_log_return("Unpublish-CDN反馈XML解析结果：".var_export($client_re,true));
                    if(is_array($client_re) && !empty($client_re))
                    {
                        $client_code = $client_re['ResultCode'];
                    }
                    else
                    {
                        $client_code = NS_CDS_FAIL;
                    }
                    if($client_code == 0)
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
                        $reason = "发送成功";
                    }
                    else
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $cdn_code = NS_CDS_CDN_FAIL;
                        $params['nns_notify_result'] = $client_code;
                        $inspur_code = array(
                            '1' => 'prc命令调用参数出错,PPC本身参数不和规范',
                            '6' => '资产（id）不存在',
                            '8' => '服务内部错误，各个进程间协作问题',
                        );
                        $reason = isset($inspur_code[$client_code]) ? $client_code.$inspur_code[$client_code] : $client_re['ResultMsg'];
                    }
                    $params['nns_notify_fail_reason'] = $reason;
                    $params['nns_notify_time'] = date('Y-m-d H:i:s');
                    $this->write_log_return($reason);
                    break;
                case 'DeleteAsset'://删除媒资
                    $cdn_code = NS_CDS_CDN_NOTIFY_SUCCE;//初始化成功
                    $local_url = '';
                    $arr_video_info = $this->get_video_info();

                    $xml_post_string  = '<?xml version="1.0" encoding="utf-8"?>';
                    $xml_post_string .= '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ing="http://IngestAssetService.homed.ipanel.cn">';
                    $xml_post_string .=      '<soapenv:Header/>';
                    $xml_post_string .=      '<soapenv:Body>';
                    $xml_post_string .=          '<ing:DeleteAsset>';
                    $xml_post_string .=              '<LSPID>'.$this->get_project_config('LSPID').'</LSPID>';
                    $xml_post_string .=              '<AMSID>'.$this->get_project_config('AMSID').'</AMSID>';
                    $xml_post_string .=              '<Sequence>'.$c2_id.'</Sequence>';
                    $xml_post_string .=              '<AssetId>'.$this->get_video_cdn_import_id().'</AssetId>';
                    $xml_post_string .=              '<ProviderID>'.$arr_video_info['base_info']['nns_producer'].'</ProviderID>';
                    $xml_post_string .=          '</ing:DeleteAsset>';
                    $xml_post_string .=      '</soapenv:Body>';
                    $xml_post_string .= '</soapenv:Envelope>';

                    $this->write_log_return("CDN调用：" . $wsdl_addr . "，DeleteAsset参数：" . $xml_post_string);

//                    $client_re = $soap_client->__doRequest($xml_post_string,$wsdl_addr,'DeleteAsset',1,0);
                    $curl = new np_http_curl_class();
                    $client_re = $curl->post($wsdl_addr,$xml_post_string);
                    $this->write_log_return("DeleteAsset-CDN同步返回：".var_export($client_re,true));
                    $client_re = $this->parse_notify_xml($client_re);
                    $this->write_log_return("DeleteAsset-CDN反馈XML解析结果：".var_export($client_re,true));
                    if(is_array($client_re) && !empty($client_re))
                    {
                        $client_code = $client_re['ResultCode'];
                    }
                    else
                    {
                        $client_code = NS_CDS_FAIL;
                    }
                    if($client_code == 0)
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $params['nns_notify_result'] = NS_CDS_CDN_NOTIFY_SUCCE;
                        $reason = "发送成功";
                    }
                    else
                    {
                        $import_code = NS_CDS_CDN_NOTIFY_SUCCE;
                        $cdn_code = NS_CDS_CDN_FAIL;
                        $params['nns_notify_result'] = $client_code;
                        $inspur_code = array(
                            '1' => 'prc命令调用参数出错,PPC本身参数不和规范',
                            '6' => '资产（id）不存在',
                            '8' => '服务内部错误，各个进程间协作问题',
                        );
                        $reason = isset($inspur_code[$client_code]) ? $client_code.$inspur_code[$client_code] : $client_re['ResultMsg'];
                    }
                    $params['nns_notify_fail_reason'] = $reason;
                    $params['nns_notify_time'] = date('Y-m-d H:i:s');
                    $this->write_log_return($reason);
                    break;
            }
//        }
//        catch (Exception $e)
//        {
//            $import_code = NS_CDS_CDN_FAIL;
//            $cdn_code = NS_CDS_CDN_FAIL;
//            $reason = '抛出异常,发送CDN失败,请联系CDS运维';
//            $this->write_log_return($reason.$e->getMessage(), $cdn_code);
//        }
        $params['nns_url'] = $local_url;
        $params['nns_result'] = $import_code;
        $params['nns_send_time'] = date("Y-m-d H:i:s");
        $params['nns_result_fail_reason'] = $reason;
        //生成C2日志
        $build_c2 = $this->build_c2_log($params);
        if($build_c2['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($build_c2['reason'], $build_c2['ret']);
        }

        return $this->is_ok($cdn_code, $reason);
    }

    /**
     * 生成xml
     * 【包含冒号的key，value为多维数组或者字符串，为XML的节点；不包含冒号的key，value为字符串，为XML的属性值】
     * @param unknown $data 数组对象
     * array(
    'adi:OpenGroupAsset' => array(
    array(
    'type' => 'VODRelease',
    'product' => 'VOD',
    'vod:VODRelease' => array(
    array(
    'providerID' => 'WASU',
    'providerType' => 2,
    'assetID' => 'CP23010020141019085900',
    'updateNum' => '',
    'groupAsset' => 'Y',
    'serialNo' => '2014112413520016',
    'adi:AssetLifetime' => array(
    array(
    'startDateTime' => '2014-10-19',
    'endDateTime' => '2064-10-19',
    ),
    ),
    ),
    ),
    ),
    ),
     * return xml
     */
    private function _make_array_xml($data)
    {
        $obj_dom = new DOMDocument("1.0", 'utf-8');
        $attr = $obj_dom->createElement("adi:ADI2");
        $attr_data = $obj_dom->appendChild($attr);
        $attr->setAttribute('xmlns','http://www.cablelabs.com/VODSchema/default');
        $attr->setAttribute('xmlns:adi','http://www.cablelabs.com/VODSchema/adi');
        $attr->setAttribute('xmlns:vod','http://www.cablelabs.com/VODSchema/vod');
        $this->_make_child_array_xml($attr, $attr_data, $obj_dom, $data);
        return $obj_dom->saveXML();
    }

    /**
     * XML子集节点生成方式
     * @param $attr
     * @param $attr_data
     * @param $obj_dom
     * @param $data
     */
    private function _make_child_array_xml($attr, $attr_data, $obj_dom, $data)
    {
        if(is_array($data))
        {
            foreach ($data as $attr_key => $value)
            {
                if(stripos($attr_key, ':') !== false && is_array($value))
                {
                    foreach ($value as $val)
                    {
                        $node_obj = $obj_dom->createElement($attr_key);
                        $node = $attr_data->appendChild($node_obj);
                        $this->_make_child_array_xml($node_obj, $node, $obj_dom, $val);
                    }
                }
                elseif(stripos($attr_key, ':') !== false && !is_array($value))
                {
                    $node_obj = $obj_dom->createElement($attr_key);
                    $node = $attr->appendChild($node_obj);
                    $content = $obj_dom->createTextNode($value);
                    $node->appendchild($content);
                }
                else
                {
                    $attr->setAttribute($attr_key,$value);
                }
            }
        }
    }

    /**
     * 注入通知反馈
     * @param $Sequence
     * @param $AssetId
     * @param $PlayId
     * @param $ResultCode
     * @param $ResultMsg
     * @return array
     */
    public function ingest_notify($Sequence,$AssetId,$PlayId,$ResultCode,$ResultMsg)
    {
        //注入成功，先更改任务状态
        $notify_re = $this->is_notify_ok($Sequence,$ResultCode,$ResultMsg);
        $this->write_log_return(var_export($notify_re,true));
        if($notify_re['ret'] != NS_CDS_SUCCE)
        {
            return $notify_re;
        }
        //注入成功，开始走发布流程
        if($ResultCode == 0)
        {
            $c2_publish_id = $this->get_guid();
            $params = array(
                'nns_task_type' => "Movie",//媒资类型
                'nns_action' => 'ONLINE', //发布
                'nns_content' => '',
                'nns_task_id' => $this->get_c2_info('id'),
                'nns_task_name' => $this->get_c2_info('name'),
            );
            $exec_re = $this->execute($params,$c2_publish_id,'Publish');
            return $this->save_exec_log($exec_re);
        }
    }

    /**
     * 发布通知反馈
     * @param $Sequence
     * @param $AssetId
     * @param $PlayId
     * @return array
     */
    public function publish_notify($Sequence,$AssetId,$PlayId)
    {
        //homed媒资注入到云平台系统后对应的视频id，播放时需要该id,来拼装播放路径。如果注入任务正在排队或者注入失败，则该值为”0”,存入contentid
        if(empty($PlayId))
        {
            $ResultCode = NS_CDS_CDN_LINE_FAIL;
            $ResultMsg = "发布失败";
        }
        else
        {
            $ResultCode = NS_CDS_CDN_NOTIFY_SUCCE;
            $ResultMsg = "发布成功";
        }

        //更改片源的content_id
        //根据信令ID获取C2任务ID
        $c2_log = \nl_c2_log::query_by_condition($this->get_dc(),array("nns_id" => $Sequence));
        if($c2_log['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($c2_log['reason'], $c2_log['ret']);
        }
        $c2_info = \nl_c2_task::query_by_condition($this->get_dc(),array("nns_id" => $c2_log['data_info'][0]['nns_task_id']));
        if($c2_info['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($c2_info['reason'],$c2_info['ret']);
        }
        $edit_media_result = $this->edit_media_info(array('nns_content_id' => $PlayId), $c2_info['data_info'][0]['nns_ref_id']);
        if($edit_media_result['ret'] != NS_CDS_SUCCE)
        {
            return $this->write_log_return($edit_media_result['reason'],$edit_media_result['ret']);
        }
        return $this->is_notify_ok($Sequence,$ResultCode,$ResultMsg);
    }

    /**
     * 解析反馈的XML数据
     * @param $xml
     * @return array|bool
     */
    private function parse_notify_xml($xml)
    {
        include_once NPDIR . "np_xml2array.class.php";
        $xml_arr = np_xml2array::getArrayData($xml);
        if($xml_arr['ret'] != 1)
        {
            $this->write_log_return('CDN反馈的XML解析失败');
            return false;
        }
        $parse_re = array();
        if(isset($xml_arr['data']['children'][0]['children'][0]['children']) && is_array($xml_arr['data']['children'][0]['children'][0]['children']))
        {
            foreach ($xml_arr['data']['children'][0]['children'][0]['children'] as $value)
            {
                $parse_re[$value['name']] = $value['content'];
            }
        }
        else
        {
            $this->write_log_return('CDN反馈的XML解析失败');
            return false;
        }
        return $parse_re;
    }
}